/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.googlecode.ivybeans.module.options;

import com.googlecode.ivybeans.facade.IvyExtensionsManager;
import com.googlecode.ivybeans.facade.IvyFileUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

import org.openide.util.Exceptions;

/**
 *
 * @author claudio
 */
public class IvyPreferences {

    public static Logger LOG = Logger.getLogger("com.googlecode.ivybeans.module");
    public static final String PROP_EXTENSION_DIR = "ivy.extensions.dir";
    public static String PROP_IVY_JAR_FILE = "ivy.jar.file";
    public static String PROP_ANTLIB_JAR_FILE = "antlib.jar.file";

    private final Preferences prefs = Preferences.userNodeForPackage(IvyPreferences.class);
    private static IvyPreferences ivyPrefs = new IvyPreferences();
    // the ivy jar path is stored as a path and File, because both are used.
    // this prevents "new File" and "file.getCanonicalPath" used
    private String ivyHomePath;
    private File ivyHomeFile;
    private File ivyExtensionsDir;

    private IvyPreferences() {
        ivyHomePath = prefs.get(PROP_IVY_JAR_FILE, null);
        if (ivyHomePath == null) {
            // the path to the ivy jar file is not found on the user preferences
            // try to discover it bundled with the ivybeans module
            LOG.info("ivy jar file not found. Discover it...");
            setIvyHomeFile(IvyFileUtil.discoverIvyJarFile());
        } else {
            setIvyHomeFile(new File(ivyHomePath));
        }
        String antlibPath = prefs.get(PROP_ANTLIB_JAR_FILE, null);
        if (antlibPath == null) {
            File antlibjar = IvyFileUtil.discoverAntlibJarFile();
            antlibPath = antlibjar.getAbsolutePath();
            prefs.put(PROP_ANTLIB_JAR_FILE, antlibPath);
        }
        String ivyExtensionsDirPath = prefs.get(PROP_EXTENSION_DIR,"");
        setIvyExtensionsDir(ivyExtensionsDirPath.isEmpty() ? null : new File(ivyExtensionsDirPath));
        // check if the settings points to a existent file on the filesystem
        checkFile(ivyHomeFile);
        checkFile(new File(antlibPath));
    }

    public static IvyPreferences getInstance() {
        return ivyPrefs;
    }

    public void setIvyHomeFile(File file) {
        // if the user try to set the same file, skip it
        if (file != null && !file.equals(ivyHomeFile)) {
            this.ivyHomeFile = file;
            setIvyHomePath(file.getAbsolutePath());
        }
    }

    public void setIvyHomePath(String path) {
        // if the user try to set the same file, skip it
        if (path != null && !path.equals(ivyHomePath)) {
            // set ivy home path, for string and File
            this.ivyHomePath = path;
            setIvyHomeFile(new File(path));
            // set the ivy path to the user preferences
            prefs.put(PROP_IVY_JAR_FILE, path);
            try {

                prefs.flush();
            } catch (BackingStoreException ex) {
                Exceptions.printStackTrace(ex);
            }
            // set a system wide property
            System.setProperty("ivy.home", path);
            LOG.fine("setIvyHomePath => " + path);
        }
    }

    public String getIvyHomePath() {
        return ivyHomePath;
    }

    public File getIvyHomeFile() {
        return ivyHomeFile;
    }

    public File getIvyExtensionsDir() {
        return ivyExtensionsDir;
    }

    public final void setIvyExtensionsDir(File ivyExtensionsDir) {
        IvyExtensionsManager.getInstance().setExtensionsDir(ivyExtensionsDir);
        this.ivyExtensionsDir = ivyExtensionsDir;
        try {
            prefs.put(PROP_EXTENSION_DIR, ivyExtensionsDir == null ? "" : ivyExtensionsDir.getCanonicalPath());
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        try {
            prefs.flush();
        } catch (BackingStoreException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    public Preferences getPrefs() {
        return prefs;
    }

    private void checkFile(File f) {
        if (!f.exists()) {
            LOG.warning("File \" " + f + "\" doesn't exist !");
        }
    }

}
